<?php


namespace app\api\controller;



use app\api\model\UserModel;
use app\api\validate\UserValidate;
use app\BaseController;


class User extends  BaseController
{
    //注册
    public function register()
    {
        //接收数据
        $data = input('post.');
        //查重
        $repeat = UserModel::where('mobile','=',$data['mobile'])->find();
        if($repeat){
            return error('手机号已注册');
        }
        //验证器
        $validate = new UserValidate();
        $res = $validate->scene('register')->check($data);
        if(!$res){
            return error($validate->getError());
        }
        //检验验证码
        $check = checkSmsCode($data['mobile'],$data['code']);
        if(!$check){
            return error('验证码错误');
        }
        //处理密码
        $randStr = createRandStr($lenth=8);
        $password = md5($data['password'].$randStr);
        $data['salt'] = $randStr;
        $data['password'] = $password;
        //入库
        if(UserModel::create($data)){
            return success('注册成功');
        }else{
            return error('注册失败');
        }

    }
//登录
    public function login(){
        $data = input('post.');
        //验证器
        $validate = new UserValidate();
        $res = $validate->scene('login')->check($data);
        if(!$res){
            return error($validate->getError());
        }
        //查看用户是否存在
        $user = UserModel::where('mobile','=',$data['mobile'])->find();
        if(!$user){
            return error('该用户不存在');
        }
        //验证密码
        if(md5($data['password'].$user['salt']) != $user['password']){
            return error('密码错误');
        }
        return success('登陆成功',[
            //JWT
            'token' => signToken($user['id'],$user['mobile']),
        ]);

    }
    public function sendCsmCode()
    {
        $mobile = input('mobile');
        //验证验证码
        $code = sendAliSms($mobile);
        if($code['code'] == 1){
            return success('发送成功');
        }else{
            return error($code['msg']);
        }
    }


}